﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Medical.Domain.Enum;
using System.ComponentModel;
using MediatR;
using Medical.Api.Read.Application.Command.BasicManagement.ShelfDictionaryCommand;
using System.Collections.Generic;
using Medical.Api.Read.Dto.BasicManagement.DeviceClassificationDictionaryDto;
using Medical.ErrorCode;
using Medical.Domain.BasicManagement;
using Medical.Api.Read.Application.Command.BasicManagement.DeviceClassificationDictionaryCommand;
using Medical.Interstructrue.Base;
using ApparatusTypeEntity = Medical.Domain.BasicManagement.ApparatusType;
using Medical.Api.Read.Dto.BasicManagement.EquipmentPackageDictionaryDto;
using Medical.Api.Read.Application.Command.BasicManagement.EquipmentPackageDictionaryCommand;

namespace Medical.Api.Read.Controllers
{
    /// <summary>
    /// 公用接口控制器（枚举、列表）
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CommonController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly IBaseRepository<ApparatusTypeEntity> _apparatusTypeRepository;
        public CommonController(IMediator mediator, IBaseRepository<ApparatusTypeEntity> apparatusTypeRepository)
        {
            _mediator = mediator;
            _apparatusTypeRepository = apparatusTypeRepository;
        }

        /// <summary>
        /// 获取供应商枚举列表
        /// </summary>
        [HttpGet]
        public IActionResult GetSupplierEnumList()
        {
            var list = GetEnumList<SupplierEnum>();
            return Ok(list);
        }

        /// <summary>
        /// 获取库房枚举列表
        /// </summary>
        [HttpGet]
        public IActionResult GetWarehouseEnumList()
        {
            var list = GetEnumList<WarehouseEnum>();
            return Ok(list);
        }

        /// <summary>
        /// 获取出库原因枚举列表
        /// </summary>
        [HttpGet]
        public IActionResult GetOutCauseEnumList()
        {
            var list = GetEnumList<OutCauseEnum>();
            return Ok(list);
        }

        /// <summary>
        /// 获取物品类型枚举列表
        /// </summary>
        [HttpGet]
        public IActionResult GetMaterialTypeEnumList()
        {
            var list = GetEnumList<MaterialTypeEnum>();
            return Ok(list);
        }

        /// <summary>
        /// 获取审批状态枚举列表
        /// </summary>
        [HttpGet]
        public IActionResult GetApprovalStateEnumList()
        {
            var list = GetEnumList<ApprovalStateEnum>();
            return Ok(list);
        }


        /// <summary>
        /// 获取货架列表
        /// </summary>
        [HttpGet]
        public async Task<List<ShelvesListDto>> GetShelvesList()
        {
            return await _mediator.Send(new GetShelvesListCommand());
        }

        /// <summary>
        /// 获取器械列表
        /// </summary>
        [HttpGet]
        public async Task<ApiResult<ApiPageIng<ApparatusListDto>>> GetApparatusList([FromQuery] QueryApparatusDto dto)
        {
            var result = await _mediator.Send(new QueryApparatusCommand(dto));
            var page = result.Data;
            var typeDict = _apparatusTypeRepository.GetAll().ToDictionary(t => t.Id, t => t.Name);
            var list = page.PageData
                .Where(x => x.Status == 1)
                .Select(x => new ApparatusListDto
                {
                    Id = x.Id,
                    ApparatusImage = x.ApparatusImage,
                    ApparatusCode = x.ApparatusCode,
                    ApparatusName = x.ApparatusName,
                    Unit = x.Unit,
                    Price = x.Price,
                    Manufacturer = x.Manufacturer,
                    Status = x.Status,
                    StatusName = x.Status == 1 ? "启用" : "禁用",
                    CategoryId = (Domain.Enum.ApparatusType)(int)x.CategoryId,
                    CategoryName = typeDict.ContainsKey(x.CategoryId) ? typeDict[x.CategoryId] : string.Empty,
                    Model = x.Model,
                    DurableProperty = x.DurableProperty
                }).ToList();
            return new ApiResult<ApiPageIng<ApparatusListDto>>
            {
                Code = result.Code,
                Msg = result.Msg,
                Data = new ApiPageIng<ApparatusListDto>
                {
                    TotalCount = page.TotalCount,
                    PageData = list,
                    PageIndex = page.PageIndex,
                    PageSize = page.PageSize
                }
            };
        }

        /// <summary>
        /// 获取器械包列表
        /// </summary>
        [HttpGet]
        public async Task<ApiResult<ApiPageIng<EquipmentPackageListDto>>> GetEquipmentPackageList([FromQuery] QueryEquipmentPackageDto dto)
        {
            var result = await _mediator.Send(new QueryEquipmentPackageCommand(dto));
            var page = result.Data;
            var list = page.PageData
                .Where(x => x.Status == 1)
                .Select(x => new EquipmentPackageListDto
                {
                    Id = x.Id,
                    PackageType = x.PackageType,
                    PackageCode = x.PackageCode,
                    PackageName = x.PackageName,
                    Model = x.Model,
                    Days = x.Days,
                    ServicePrice = x.ServicePrice,
                    SterilizationMethod = (SterilizationEnum)x.SterilizationMethod,
                    SterilizationMethodName = GetEnumDescriptionSafe(typeof(SterilizationEnum), x.SterilizationMethod),
                    OuterPackaging = (OuterPackEnum)x.OuterPackaging,
                    OuterPackagNmae = GetEnumDescriptionSafe(typeof(OuterPackEnum), x.OuterPackaging),
                    PackagingType = (PaekagEnum)x.PackagingType,
                    PackagingTypeName = GetEnumDescriptionSafe(typeof(PaekagEnum), x.PackagingType),
                    Status = x.Status,
                    StatusName = x.Status == 1 ? "启用" : "禁用",
                    PackageImage = x.PackageImage,
                    Barcodes = x.Barcodes
                }).ToList();
            return new ApiResult<ApiPageIng<EquipmentPackageListDto>>
            {
                Code = result.Code,
                Msg = result.Msg,
                Data = new ApiPageIng<EquipmentPackageListDto>
                {
                    TotalCount = page.TotalCount,
                    PageData = list,
                    PageIndex = page.PageIndex,
                    PageSize = page.PageSize
                }
            };
        }


        private List<object> GetEnumList<T>() where T : Enum
        {
            var type = typeof(T);
            var values = Enum.GetValues(type);
            var list = new List<object>();
            foreach (var value in values)
            {
                list.Add(new
                {
                    Value = (int)value,
                    Name = value.ToString()
                });
            }
            return list;
        }

        private static string GetEnumDescription(Enum value)
        {
            var field = value.GetType().GetField(value.ToString());
            var attr = (DescriptionAttribute)Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
            return attr != null ? attr.Description : value.ToString();
        }

        // 新增安全的枚举Description获取方法
        private static string GetEnumDescriptionSafe(Type enumType, int value)
        {
            var name = Enum.GetName(enumType, value);
            if (name == null) return value.ToString();
            var field = enumType.GetField(name);
            if (field == null) return value.ToString();
            var attr = (DescriptionAttribute)Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
            return attr != null ? attr.Description : value.ToString();
        }
    }
}
